/*
 * example.c
 *
 *  Created on: Jul 17, 2021
 *      Author: dbw
 */

#include <string.h>
#include <stdint.h>
#include "math_util.h"

#define LOG_TAG     "example_string"
#define LOG_LEVEL    LOG_LEVEL_VERBOSE
#include "logger.h"

#include "examples.h"

#define GPS_RMC "$GNRMC,122921.000,A,3204.862246,N,11845.911047,E,0.099,191.76,280521,,E,A*00"

void split_string_example(void)
{
    char buf[128];
    int buf_len;
    char *token = NULL;
    char *saveptr = NULL;
    const char *delim = ",*";

    LOG_I("test split string");

    buf_len = snprintf(buf, sizeof(buf), "%s", GPS_RMC);

    token = strtok_r(buf, delim, &saveptr);
    while (token)
    {
        LOG_D("%s", token);
        token = strtok_r(NULL, delim, &saveptr);
    }

    LOG_HEX_V(buf, buf_len, "finally, buf:");
}

static int split_string(char *str, const char *delim, char *sub_ptr[], int size)
{
    char *token = NULL;
    char *saveptr = NULL;
    int idx = 0;


    token = strtok_r(str, delim, &saveptr);
    while (token && idx < size)
    {
        sub_ptr[idx++] = token;
        token = strtok_r(NULL, delim, &saveptr);
    }

    return idx;
}

void split_string_example2(void)
{
    char buf[128];
    char *sub_buf[20];
    int num;

    LOG_I("test split string 2");

    snprintf(buf, sizeof(buf), "%s", GPS_RMC);
    num = split_string(buf, ",", sub_buf, ARRAY_SIZE(sub_buf));

    if (num < 7)
    {
        LOG_E("fail");
        return;
    }

    LOG_D("succeed, valid:%s, latitude:%s, longitude:%s", sub_buf[2], sub_buf[3], sub_buf[5]);

}

static void parse_gps(const char *gps)
{
    char valid = ' ';
    double longitude = 0;
    double latitude = 0;
    int ret;

    ret = sscanf(gps,
             "$GNRMC,%*[^,],%c,%lf,%*c,%lf,%*c,",   /* UTC,valid,latitude,ns,longitude,ew,  */
             &valid, &latitude, &longitude);

    LOG_D("parse gps(%s)", gps);


    if (ret != 3)
    {
        LOG_E("fail");
    }
    else
    {
        LOG_D("succeed, valid:%c, latitude:%lf, longitude:%lf", valid, latitude, longitude);
    }
}

void parse_string_example(void)
{
    const char *strs[] =
    {
            "$GNRMC,122921.000,A,3204.862246,N,11845.911047,E,0.099,191.76,280521,,E,A*00",
            "hello world",
            "$GNRMC,,,,,,,,,,,,*00"
    };

    LOG_I("test parse string");

    for (int i = 0; i < ARRAY_SIZE(strs); i++)
    {
        parse_gps(strs[i]);
    }

}

#ifdef EXAMPLE_SHOW_STRING

void string_example_run(void)
{
//    split_string_example();
//    split_string_example2();
//    parse_string_example();
}

#else

void string_example_run(void)
{

}

#endif /* EXAMPLE_SHOW_STRING */
